﻿using StudyKitLib;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MainModule
{
    public partial class Form1 : Form
    {
        ServiceReference2.Container context = 
            new ServiceReference2.Container(new Uri("http://localhost:47318/odata"));

        public static long PortNO;
        public static RF1356.REPLY reply;
        ObservableCollection<string> RFIDUID = new ObservableCollection<string>();
        public Form1()
        {
            InitializeComponent();
            
        }

        private void btnPortOpen_Click(object sender, EventArgs e)
        {
            try
            {
                int port = cmbPort.SelectedIndex + 1;

                if (!RF1356.RFReaderOpen(port))
                {
                    MessageBox.Show("COM Port Open Fail", "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
                }
                else
                {
                    cmbPort.Enabled = false;
                    //btnAutoOpen.Enabled = false;
                    btnPortOpen.Enabled = false;
                    btnPortClose.Enabled = true;
                    btnReadSerialNO.Enabled = true;
                    chkAuto.Enabled = true;
                    PortNO = port;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            int i;

            for (i = 1; i < 11; i++)    // COM1~10            
                cmbPort.Items.Add("COM" + i.ToString());

            for (i = 1; i < 11; i++)    // Timer Interval : 100~1000            
                cmbInterval.Items.Add((i * 100).ToString());

           

            cmbPort.SelectedIndex = 0;
            cmbInterval.SelectedIndex = 4;
            
        }
        
        private void btnReadSerialNO_Click(object sender, EventArgs e)
        {
            int tagCnt = 0;
            string SerialNumbers = String.Empty;

            grdView1.Rows.Clear();
            //lblCount.Text = "00";
            
            reply = RF1356.RFReadSerialNO(PortNO, ref SerialNumbers);

            switch (reply)
            {
                case RF1356.REPLY.RF_OK:
                    //lblCount.Text = SerialNumbers.Substring(0, 2);
                    tagCnt = int.Parse(SerialNumbers.Substring(0, 2));

                    for (int i = 0; i < tagCnt; i++)
                    {
                        string str = SerialNumbers.Substring(2 + (16 * i), 16);
                        string UID = String.Empty;
                        string UIDED = string.Empty;
                        string Maker = String.Empty;
                        
                        for (int j = 0; j < 8; j++)
                        {
                            UID = str.Substring(2 * j, 2) + UID;
                        }

                        Maker = UID.Substring(2, 2);

                        switch (Maker)
                        {
                            case "04":
                                Maker = "PHILIPS";
                                break;

                            case "05":
                                Maker = "INFINEON";
                                break;

                            case "07":
                                Maker = "TI";
                                break;

                            default:
                                break;
                        }
                        
                        //lstUID1.Items.Add(UID); 

                      
                         grdView1.Rows.Add(new string[] { UID, Maker });

                         //Grid2();

                        //foreach (var kkk in RFIDUID)
                        //{
                        //    if(kkk!=UID)
                        //    {
                        //        RFIDUID.Add(UIDED);
                        //    }
                        //    else
                        //    {
                        //        MessageBox.Show("같네요");
                        //    }
                        //}



                        if ((i % 2) == 0)
                        {
                            grdView1[0, i].Style.BackColor = Color.Aqua;
                            grdView1[1, i].Style.BackColor = Color.Aqua;
                        }
                        else
                        {
                            grdView1[0, i].Style.BackColor = Color.LightSteelBlue;
                            grdView1[1, i].Style.BackColor = Color.LightSteelBlue;
                        }
                    }

                    //if (chkSnd.Checked)
                    //    PlaySuccess();

                    //if (!chkAuto.Checked)
                    //{
                    //    btnReadData.Enabled = true;
                    //    btnWriteData.Enabled = true;
                    //}
                    break;

                case RF1356.REPLY.NO_TRANSPONDER:
                    //if (chkSnd.Checked)
                    //    PlayFail();
                    grdView1.Rows.Add(new string[] { "No Tag", "" });
                    break;

                case RF1356.REPLY.RF_ERR:
                    //if (chkSnd.Checked)
                    //    PlayFail();

                    grdView1.Rows.Add(new string[] { "Error", "" });

                    break;

                default:
                    break;
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Interval = int.Parse(cmbInterval.Text);

            btnReadSerialNO_Click(sender, e);
        }
        private void chkAuto_CheckedChanged(object sender, EventArgs e)
        {
            if (chkAuto.Checked)
            {
                timer1.Enabled = true;

                btnPortClose.Enabled = false;
                btnReadSerialNO.Enabled = false;
                //btnReadData.Enabled = false;
                //btnWriteData.Enabled = false;
            }
            else
            {
                timer1.Enabled = false;

                btnPortClose.Enabled = true;
                btnReadSerialNO.Enabled = true;
               // btnReadData.Enabled = true;
                //btnWriteData.Enabled = true;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Product_Move pm = new Product_Move();
            pm.ShowDialog();
        }


        private void button4_Click(object sender, EventArgs e)
        {
            productSet ps = new productSet();
            ps.ShowDialog();

            //MessageBox.Show(obj);

            
        }

        public static string obj;
        public static string obj2;

        private void grdview1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            obj = grdView1[0, grdView1.CurrentRow.Index].Value.ToString();
        }


        private void grdView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            //obj2 = grdView1[0, 0].Value.ToString();

            //MessageBox.Show(obj2);
        }



        private void button1_Click(object sender, EventArgs e)
        {
            ContainerBox cb = new ContainerBox();
            cb.ShowDialog();
        }

        private void cmbPort_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void btnPortClose_Click(object sender, EventArgs e)
        {
            try
            {
                if (RF1356.RFReaderClose(PortNO))
                {
                    //btnAutoOpen.Enabled = true;
                    btnPortOpen.Enabled = true;
                    btnPortClose.Enabled = false;
                    btnReadSerialNO.Enabled = false;
                   // btnReadData.Enabled = false;
                  //  btnWriteData.Enabled = false;
                    cmbPort.Enabled = true;
                    chkAuto.Enabled = false;

                    try
                    {
                        if (RF1356.RFReaderIsOpen(PortNO))
                            RF1356.RFReaderClose(PortNO);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
           Grid2();

            
        }

        public void Grid2()
        {
            string UID = obj;
            string DataBlocks = String.Empty;
            string Data = String.Empty;

            reply = RF1356.RFReadDataBlock(PortNO, UID, ref DataBlocks, 0, 10);

            //MessageBox.Show(RF1356.hex2str(DataBlocks));

            var conDataBlocks = RF1356.hex2str(DataBlocks);

            var pm = context.ProductMoves.Where(kkk => kkk.ProductMoveId == Convert.ToInt32(conDataBlocks)).SingleOrDefault();

            var pmp = Convert.ToInt32(pm.ProductNo);

            var ps = context.Products.Where(kkk => kkk.ProductNo == pmp).Single();

            grdView2.Rows.Add(new string[] { pm.ProductMoveId.ToString(), ps.ProductName, pm.ProductMoveQuantity.ToString(), pm.ProductMoveDate.ToString(), pm.ProductMoveState });



        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            grdView2.Rows.RemoveAt(grdView2.CurrentRow.Index);

            string UID = obj;
            string DataBlocks = String.Empty;
            string Data = String.Empty;

            reply = RF1356.RFReadDataBlock(PortNO, UID, ref DataBlocks, 0, 10);

            //MessageBox.Show(RF1356.hex2str(DataBlocks));

            var conDataBlocks = RF1356.hex2str(DataBlocks);

            var pm = context.ProductMoves.Where(kkk => kkk.ProductMoveId == Convert.ToInt32(conDataBlocks)).SingleOrDefault();

            var pmp = Convert.ToInt32(pm.ProductNo);

            var ps = context.Products.Where(kkk => kkk.ProductNo == pmp).Single();

            grdView2.Rows.Add(new string[] { pm.ProductMoveId.ToString(), ps.ProductName, pm.ProductMoveQuantity.ToString(), pm.ProductMoveDate.ToString(), "입고" });

            pm.ProductMoveState = "입고";

            context.UpdateObject(pm);
            context.SaveChanges();

            MessageBox.Show("이동번호 [" + pm.ProductMoveId.ToString() + "] 의 상태가 입고로 변경되었습니다. \n 카드의 정보는 초기화 됩니다.", "변경 메세지");


           
        }

    }
    public partial class RFIDList
    {
        public string UID { get; set; }
        public string Maker { get; set; }
    }
}
